import 'package:flutter/material.dart';
import 'package:wayofdressing/all_information/user_information.dart';
import 'package:wayofdressing/good_method/show_dialog.dart';
import 'package:wayofdressing/screens/login_screen.dart';
import 'package:wayofdressing/screens/register_screen.dart';
import 'package:wayofdressing/dio/configureDio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dio/dio.dart';
import 'package:wayofdressing/dio/UserDio.dart';
import 'package:wayofdressing/main_navigator_widget.dart';
import 'package:wayofdressing/all_information/user_information.dart';

class InitScreen extends StatefulWidget {
  const InitScreen({super.key});

  static const String id = 'InitScreen';

  @override
  State<InitScreen> createState() => _InitScreenState();
}

class _InitScreenState extends State<InitScreen> {
  bool _isLoading = true; // 用于显示加载状态

  @override
  void initState() {
    super.initState();
    _loginBySavedCredentials(); // 加载保存的用户名和密码
  }

  // 显示加载状态
  Widget _buildLoading() {
    return Center(
      child: CircularProgressIndicator(),
    );
  }
  // 自动登录
  void _loginBySavedCredentials() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    password = prefs.getString('password')??'';
    account=prefs.getString('account')??'';

    if (account != '' && password != '') {
      try {
        Response<dynamic> response = await getUserByAccount(account, dio);
        dynamic responseData = response.data;
        if (responseData != null && responseData['success'] == true) {
          dynamic userData = responseData['data'];
          print(userData);
          if (userData != null && userData['password'] == password) {
            // 登录成功，跳转到主页面
            Navigator.pushReplacementNamed(context, MainNavigatorWidget.id);
            return;
          } else {
            ShowDialog.showErrorAndDetail(context,'登录失败，密码已更改');
          }
        } else {
          String errorMsg = responseData['errorMsg'] ?? '未知错误';
          ShowDialog.showErrorAndDetail(context,'登录失败，$errorMsg');
        }
      } catch (e) {
        print('Error: $e');
        ShowDialog.showErrorAndDetail(context,'登录失败，发生未知错误');
      }
    }
    setState(() {
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: _isLoading
          ? _buildLoading() // 显示加载状态
          : Padding(
        padding: const EdgeInsets.symmetric(horizontal: 50.0),
        child: Stack(
          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Expanded(
                        child: Hero(
                          tag: 'logo',
                          child: Container(
                            child: Image.asset(
                              'images/peanutB.png',
                            ),
                          ),
                        ),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Expanded(
                        flex: 3,
                        child: Container(
                          child: Image.asset(
                            'images/peanutB1.jpg',
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                SizedBox(
                  height: 80,
                ),
                Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(25), // 圆角半径
                    border: Border.all(
                      color: Colors.black, // 边框颜色
                      width: 2, // 边框宽度
                    ),
                  ),
                  child: TextButton(
                    child: Text(
                      '登录',
                      style: TextStyle(color: Colors.black, fontSize: 32),
                    ),
                    onPressed: () {
                      Navigator.pushNamed(context, LoginScreen.id);
                    },
                  ),
                ),
                SizedBox(
                  height: 30,
                ),
                Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(25), // 圆角半径
                    border: Border.all(
                      color: Colors.black, // 边框颜色
                      width: 2, // 边框宽度
                    ),
                  ),
                  child: TextButton(
                    child: Text(
                      '注册',
                      style: TextStyle(color: Colors.black, fontSize: 32),
                    ),
                    onPressed: () {
                      Navigator.pushNamed(context, RegisterScreen.id);
                    },
                  ),
                ),
              ],
            ),
            Positioned(
              bottom: 15,
              left: 0,
              right: 0,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('找回密码',style: TextStyle(color: Colors.black,fontSize: 16),),
                  SizedBox(width: 20,),
                  Text('更多帮助',style: TextStyle(color: Colors.black,fontSize: 16),),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
